<template>
    <div>
        <el-row :gutter="20" v-if="name = 'third'">
            <el-col :span="7">
                <el-card>
                    <div slot="header"
                        style="display: flex;flex-direction: row;justify-content: space-between; align-items: center;width: 100%;">
                        <div>门禁系统配置</div>
                        <div class="ed-button ed_black-bottom" style="cursor: pointer;" @click="synchronizate">
                            <svg-icon icon-class="synchronizate" />同步
                        </div>
                    </div>
                    <el-tree v-if="isActiveted" ref="elTree" node-key="key" highlight-current :props="defaultProps"
                        @node-click="clickCodeType" :load="loadNode" lazy></el-tree>
                </el-card>
            </el-col>
            <el-col :span="17">
                <el-card>
                    <div>
                        <el-breadcrumb separator-class="el-icon-arrow-right">
                            <el-breadcrumb-item v-for="(item, index) in allParent" :to="{ path: '/' }" :key="index">
                                {{ item.lable }}</el-breadcrumb-item>
                        </el-breadcrumb>
                    </div>
                    <div>
                        <el-form label-position="left" label-width="80px">
                            <el-row :gutter="20" v-for="(item, index) in checkfigQueryForm.accessControlList"
                                :key="index" style="margin-left:0; margin-right:0">
                                <el-col :span="9">
                                    <el-form-item label="门禁名称">
                                        <el-input class="flex-input" placeholder="请输入" v-model="item.deviceName"
                                            style="width:100%"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="9">
                                    <el-form-item label="门禁设备">
                                        <EdSelect :selectParams="createSelectParamsForItem(item)" filterable
                                         v-model="item.deviceId" style="width:100%"></EdSelect>
                                        <!-- <el-input class="flex-input" placeholder="请输入" v-model="item.id"></el-input> -->
                                    </el-form-item>
                                </el-col>
                                <el-button v-if="checkfigQueryForm.accessControlList.length > 1" type="info"
                                    @click="delAccessContro(index, item)" class="ed_button_delete ed_delete_bottom "
                                    icon="el-icon-delete" style="margin-top: 4px;"></el-button>
                                <el-button type="info" @click="addAccessContro" class="ed_button ed_black-bottom "
                                    icon="el-icon-plus" style="margin-top: 4px;"></el-button>
                            </el-row>
                        </el-form>
                    </div>
                </el-card>
            </el-col>
        </el-row>
        <div class="projectButton">
            <el-button class="ed-button ed_black-bottom" @click="addDeviceList()">确定</el-button>
            <el-button class="ed-button ed_white_bottom" @click="$utilsSet.goBack($router)">取消</el-button>
        </div>
    </div>
</template>

<script>
import EdSelect from 'src/components/EdSelect.vue'
import { queryDeviceList, deleteDeviceList, addDeviceList, CheckDeviceList, infoTree, synchronizate, openService, closeService } from "../api";
export default {
    components: { EdSelect },
    props: {
        thirdActive: false
    },
    data() {
        return {
            isActiveted: false,
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            // 门禁系统设置新增请求参数
            checkfigQueryForm: {
                accessControlList: [
                    {
                        name: '',
                        deviceId: '',
                        deviceName: '',
                        buildingId: '',
                        orgId: this.$store.getters.vid,
                        unitId: '',
                        villageId: this.$route.query.villageId,
                    }
                ]
            },
            allParent: [],
            treeData: [],
            deviceList: [],
            // 门禁设备下拉框数据
            configQueryForm: {
                buildingId: "",
                orgId: this.$store.getters.vid,
                unitId: "",
                villageId: this.$route.query.villageId,
                deviceDevType: 8
            },
            // 门禁系统配置回显请求参数
            queryDeviceForm: {
                name: '',
                deviceId: '',
                buildingId: '',
                stagesId: '',
                orgId: this.$store.getters.vid,
                unitId: '',
                villageId: this.$route.query.villageId,
                deviceDevType: 8
            },
            // 门禁设备删除参数
            delConfigQueryForm: {
                id: '',
                buildingId: "",
                deviceId: "",
                name: "",
                orgId: this.$store.getters.vid,
                orgName: this.$store.getters.orgName,
                unitId: "",
                villageId: this.$route.query.villageId
            },
        }
    },
    mounted() {
        this.init()
    },
    activated() {
        this.init()
    },
    deactivated() {
        this.isActiveted = false
        // 门禁系统配置确定参数
        this.checkfigQueryForm.accessControlList = [
            {
                name: '',
                deviceId: '',
                buildingId: '',
                stagesId: '',
                orgId: this.$store.getters.vid,
                orgName: this.$store.getters.orgName,
                unitId: '',
                villageId: this.$route.query.villageId,
                deviceDevType: 8
            }
        ]
        this.queryDeviceForm.buildingId = ''
        this.queryDeviceForm.unitId = ''
        this.queryDeviceForm.stagesId = ''
        this.buildingName = ''
        this.stagesName = ''
        this.unitName = ''
        this.checkfigQueryForm.accessControlList = []
        this.deviceList = []
        this.treeData = []
        this.allParent = []
    },
    methods: {
        init() {
            this.deviceList = []
            this.treeData = []
            this.allParent = []

            if (this.$route.query.villageId) {
                this.queryDeviceForm.villageId = this.$route.query.villageId
                this.CheckDeviceList()
                this.refreshDeviceList()
                this.allParent.push({ id: 1, lable: this.$route.query.villageName })
                console.log(this.allParent);
            }
            this.isActiveted = true
        },
        clickCodeType(data, node) {
            // 点击左边树的时候调用下拉框
            this.allParent = []
            this.currentClickType = data.type
            if (data.type == 'unit') {
                // 新增点保存的时候传给后端的数据
                this.stagesName = node.parent.parent.data.name
                this.buildingName = node.parent.data.name
                this.unitName = data.name
                // 查询单元
                this.queryDeviceForm.buildingId = node.parent.data.id
                this.queryDeviceForm.unitId = data.id
                this.queryDeviceForm.stagesId = node.parent.parent.data.id
                this.CheckDeviceList()
            } else if (data.type == 'village') {
                this.queryDeviceForm.buildingId = ''
                this.queryDeviceForm.unitId = ''
                this.queryDeviceForm.stagesId = ''
                this.CheckDeviceList()
            } else {
                this.queryDeviceForm.buildingId = ''
                this.queryDeviceForm.unitId = ''
                this.queryDeviceForm.stagesId = ''
                this.checkfigQueryForm.accessControlList = []
            }
            // 获取所有节点，在右边显示
            this.getALL(node)
            // 根据id排序
            this.allParent.sort(function (a, b) {
                return a.id - b.id
            })
        },
        // 刷新某个树节点，重点
        async loadNode(node, resolve) {
            console.log(node);
            if (node.level === 0) {
                return resolve([{ id: this.$route.query.villageId, name: this.$route.query.villageName, type: 'village', key: this.$route.query.villageId }])
            }
            const id = node.data?.id
            const type = ['village', 'stages', 'building', 'unit', 'room'][node.level]
            if (!type || type == 'room') {
                return resolve([])
            }
            let res = await this.infoTree(id, type)
            if (node && node.id == 0) {
                this.resolve = resolve
            }
            if (type == 'unit') {
                res.isLeaf = false
            }
            resolve(res)
        },
        // 树数据处理
        async infoTree(id, type) {
            const orgId = this.$store.getters.vid ?? ''
            const result = await infoTree({ orgId: orgId, type: type, id: id })
            const meansure = {
                village: '',
                stages: '期',
                building: '栋',
                unit: '单元',
                room: '室'
            }[type]
            result.data.forEach(d => {
                d.isLeaf = !d.childType
                d.name += meansure
                d.key = type + ':' + d.id
            })
            return result.data
        },
        // 门禁设备新增一项门禁名称跟门禁设备
        addAccessContro() {
            let params = {
                orgId: this.$store.getters.vid,
                orgName: this.$store.getters.orgName,
                villageId: this.$route.query.villageId,
                deviceDevType: 8,
                name: '', deviceId: '', deviceName: '',

            }
            this.checkfigQueryForm.accessControlList.push(params)
        },
        // 门禁设备删除数组某一项
        delAccessContro(index, item) {
            if (item.deviceId) {
                this.delConfigQueryForm.id = item.id
                this.delConfigQueryForm.deviceId = item.deviceId
                deleteDeviceList(this.delConfigQueryForm).then(response => {
                    if (response.success) {
                        this.refreshDeviceList()
                    }
                })
            }
            this.checkfigQueryForm.accessControlList.splice(index, 1)
        },
        // 门禁设备新增的接口
        addDeviceList() {
            this.checkfigQueryForm.accessControlList.forEach(x => {
                x.buildingId = this.queryDeviceForm.buildingId
                x.buildingName = this.buildingName
                x.unitId = this.queryDeviceForm.unitId
                x.unitName = this.unitName
                x.stagesId = this.queryDeviceForm.stagesId
                x.stagesName = this.stagesName
                x.villageId = this.$route.query.villageId
                x.villageName = this.$route.query.villageName
                x.deviceDevType = 8
            })
            addDeviceList(this.checkfigQueryForm.accessControlList).then(response => {
                if (response.success) {
                    this.$message.success({
                        message: '门禁系统配置成功！',
                        duration: 2000,
                        center: true
                    });
                    this.$router.back()
                }
            })
        },

        getALL(node) {
            console.log(node)
            if (node.label) {
                this.allParent.push({ id: node.id, lable: node.label })
            }
            if (node.parent) {
                this.getALL(node.parent)
            }
        },
        // 门禁系统配置设备下拉框数据的接口
        refreshDeviceList() {
            queryDeviceList(this.configQueryForm).then(response => {
                if (response.success) {
                    let options = response.data.map(x => {
                        if (x.binding && x.binding == 1) {
                            // 这里设置 如果 bingding==1 就禁用 
                            return { label: x.name, value: x.deviceId, disabled: true }
                        } else {
                            return { label: x.name, value: x.deviceId, disabled: false }
                        }
                    })
                    this.deviceList = options
                    console.log('options', this.deviceList);
                }
            })
        },
        createSelectParamsForItem(item) {
            if (!item.deviceId || this.deviceList.some(d => d.value === item.deviceId)) {
                return {
                    options: this.deviceList,
                    placeholder: "请选择"
                }
            } else {
                return {
                    options: [{label: '无匹配设备', value: item.deviceId}, ...this.deviceList],
                    placeholder: "请选择"
                }
            }
        },
        // 门禁系统配置回显接口，在tab栏切换的时候调用
        CheckDeviceList() {
            CheckDeviceList(this.queryDeviceForm).then(response => {
                if (response.success) {
                    if (response.data.length > 0) {
                        this.checkfigQueryForm.accessControlList = response.data
                    } else {
                        this.checkfigQueryForm.accessControlList = []
                        this.addAccessContro()
                    }
                }
            })
        },
        synchronizate() {
            // 调同步的接口
            synchronizate({ villageId: this.$route.query.villageId }).then(response => {
                if (response.success) {
                    this.$message.success({
                        message: '设备同步成功！',
                        duration: 2000,
                        center: true
                    });
                    this.refreshDeviceList()
                } else {
                    this.$message.success({
                        message: '设备同步失败！',
                        duration: 2000,
                        center: true
                    });
                }
            })
        }
    }
}
</script>

<style lang="scss">
.projectButton {
    width: 100%;
    margin-left: 115px;
    margin-top: 50px;
}
</style>